package com.xiaotao.Interceptor;

import com.alibaba.fastjson.JSONObject;

import com.xiaotao.utils.JWTUtil;
import com.xiaotao.utils.ResponseEnum;
import com.xiaotao.utils.ResponseUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/*
* 1.用户是否登录  是否存在token 为空  返回值 false
* 2.token是否有效*/
@Component
@Slf4j
public class JWTInterceptor implements HandlerInterceptor {
   @Resource
   private  StringRedisTemplate stringRedisTemplate;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        response.setContentType("application/json;charset=utf-8");
        String token = request.getHeader("token");
        if(token == null){
            log.error("token为空验证失败");
            response.getWriter().write(JSONObject.toJSONString(ResponseUtil.get(ResponseEnum.USER_LOGIN_MISSING)));
            return false;
        }
        try{
            boolean flag = JWTUtil.verifyToken(token);
            if(!flag){
                log.error("token无效");
                response.getWriter().write(JSONObject.toJSONString(ResponseUtil.get(ResponseEnum.USER_LOGIN_MISSING)));
                return false;
            }
        }catch (Exception e){
            log.error("token无效");
            response.getWriter().write(JSONObject.toJSONString(ResponseUtil.get(ResponseEnum.USER_LOGIN_MISSING)));
            return false;
        }
        Map <String,Object> map = JWTUtil.getPayload(token);
        Integer userId = Integer.parseInt(map.get("id").toString());
        String redisToken = stringRedisTemplate.opsForValue().get("jwt:token" + userId);
        if(!token.equals(redisToken)){
            log.error("过期");
            response.getWriter().write(JSONObject.toJSONString(ResponseUtil.get(ResponseEnum.USER_LOGIN_MISSING)));
            return false;
        }
        stringRedisTemplate.opsForValue().set("jwt:token" + userId,token,60,TimeUnit.DAYS);
        return true;
    }
}


